import React from 'react';
import {  connect } from 'react-redux';
import classNames from 'classnames';
import { Button, Form, Radio, Input, Row, Col, message, Upload, Icon,Tabs } from 'antd';
import { putPW, _validate, updateUser, changePage, fetchPortrait, API_URL, PORTRAIT, formItemLayout,check_rules,checkExists } from '../../store/actions';

const RadioGroup = Radio.Group,
    RadioButton = Radio.Button,
    createForm = Form.create,
    FormItem = Form.Item;


class __pane1 extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props.user,
            rules: this.props.rules
        };
        this.handleSubmit = this.handleSubmit.bind(this);
        this.checkForm = this.checkForm.bind(this);
    }
    handleSubmit(e) {
        e.preventDefault();
        const _this = this;

        const values = _this.props.form.getFieldsValue()
        _this.props.dispatch(updateUser(values,function(){
            message.success('修改个人资料成功',1);
        },function(res){
            message.error(res.head.msg,1)
        }))

/*
        _this.props.form.validateFields((errors, values) => {
            if (!!errors) {
                message.error('表单里有格式错误',1);
                return;
            }
            try{
                _this.props.dispatch(updateUser(values,function(){
                    message.success('修改个人资料成功',1);
                },function(res){
                    message.error(res.head.msg,1)
                }))
            }catch(e){}
        });*/
    }
    componentWillMount(){
    }
    checkForm(a, b, rule, value, callback) {
        const _this = this;
        const _r = eval(_this.state.rules[a][b]['expr']),
            msg = _this.state.rules[a][b]['rule'];
        (function () {
            const result = _r.test(value);
            if (!result && value) {
                callback(msg)
            } else {
                callback();
            }
        })()
    }
    //检查手机号格式
    checkMob(rule, value, callback) {
        this.checkForm('common', 'mobile', rule, value, callback)
    }
    //检查是否已经存在，存在是否是自己的
    mobExists(rule, value, callback) {
        const _this = this;
        if(value === this.state.user.user.mobile)
            return;
        if (_this.props._target) {
            this.props.dispatch(checkExists('mobile', rule, value, callback, _this.props._target.mobile))
        } else {
            this.props.dispatch(checkExists('mobile', rule, value, callback))
        }
    }
    render(){
        let previous = {},
          isUser = '';
        if(this.state.user){
            previous = this.state.user.user;
            isUser = this.state.user.user.type == 1
        }else{
            this.props._r.push('/login');
        }
        const { getFieldProps } = this.props.form;

        const idCardProps = getFieldProps('idcard', {
            rules: [
                {min: 18,max:18, message: '身份证号是18位' }
            ],
            initialValue: previous.idcard
        });
        const mobProps = getFieldProps('mobile', {
            rules: [
                { required: false, min: 11,max:11, message: '请输入手机号' },
                {validator: this.checkMob.bind(this)},
                {validator: this.mobExists.bind(this)}
            ],
            validateTrigger: 'onBlur',
            initialValue: previous.mobile
        });
        const nickProps = getFieldProps('nickname', {
            rules: [
                { required: false,max:16, message: '昵称不得超过16个字' }
            ],
            trigger: ['onBlur'],
            initialValue: previous.nickname
        });
        const nameProps = getFieldProps('name', {
            rules: [
                { required: false,max:16, message: '姓名不得超过16个字' }
            ],
            trigger: ['onBlur'],
            initialValue: previous.name
        });
        const genderProps = getFieldProps('gender', {
            rules: [
                { required: false, message: '请选择性别' }
            ],
            initialValue: previous.gender
        });
        const emailProps = getFieldProps('mail', {
            validate: [{
                rules: [
                    { required: false }
                ],
                trigger: 'onBlur'
            }, {
                rules: [
                    { type: 'email', message: '请输入正确的邮箱地址' }
                ],
                trigger: ['onBlur']
            }],
            initialValue: previous.mail
        });
        return (
            <div>
                <Form horizontal form={this.props.form}>
                    <Row>
                        <Col>
                            <FormItem
                                {...formItemLayout}
                                label="姓名"
                            >
                                <Input {...nameProps} placeholder="请输入姓名" />
                            </FormItem>
                            <FormItem
                              {...formItemLayout}
                                label="昵称"
                            >
                                <Input {...nickProps} placeholder="请输入昵称" />
                            </FormItem>
                            <FormItem
                              {...formItemLayout}
                                label="手机号"
                            >
                                <Input {...mobProps} disabled={!isUser} placeholder="请输入手机号" />
                            </FormItem>
                            <FormItem
                              {...formItemLayout}
                                label="身份证号"
                            >
                                <Input {...idCardProps} placeholder="请输入身份证号" />
                            </FormItem>
                            <FormItem
                              {...formItemLayout}
                                label="性别"
                            >
                                <RadioGroup {...genderProps}>
                                    <RadioButton value="M">男</RadioButton>
                                    <RadioButton value="F">女</RadioButton>
                                </RadioGroup>
                            </FormItem>
                            <FormItem
                              {...formItemLayout}
                                label="电子邮件"
                            >
                                <Input {...emailProps} placeholder="请输入email" />
                            </FormItem>
                            <FormItem wrapperCol={formItemLayout.noLabel}>
                                <Button type="primary" onClick={this.handleSubmit}>提交修改</Button>
                            </FormItem>
                        </Col>
                    </Row>
                </Form>
            </div>
        )
    }
}
export const _pane1 = createForm()(__pane1);
class __pane2 extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            user: this.props.user,
            fileList:{}
        };
        this.handleChange = this.handleChange.bind(this);
        this.normFile = this.normFile.bind(this)
    }
    normFile(e){
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    handleChange(info){
        //if (info.file.status !== 'uploading') {}
        if (info.file.status === 'done') {
            message.success(`${info.file.name} 上传成功。`);
            this.props.dispatch(fetchPortrait(this.props.user.user.account_id))
        } else if (info.file.status === 'error') {
            message.error(`${info.file.name} 上传失败。`);
        }
    }
    componentWillMount(){
        this.props.dispatch(fetchPortrait(this.props.user.user.account_id))
    }
    componentWillReceiveProps(nextProp){
        this.setState({
            portrait:nextProp.portrait.url
        })
    }
    render(){
        const { getFieldProps } = this.props.form;
        const upload1 = getFieldProps('upload', {
            valuePropName: 'portrait',
            normalize: this.normFile,
            onChange: this.handleChange,
            rules: [
                { required: true,
                    message: '必须上传有效头像' }
            ]
        });
        return (
            <div>
                <Form horizontal onSubmit={this.handleSubmit}>
                    <FormItem
                        label="上传头像"
                        labelCol={{ span: 6 }}
                        wrapperCol={{ span: 18 }}
                        help="请上传头像图片"
                    >
                        <Upload
                            name="portrait"
                            showUploadList={false}
                            action= {`${API_URL}${PORTRAIT}?accessToken=${this.props.user.accessToken}`}
                            {...upload1}
                        >
                            <div style={{
                                width: '100px',
                                overflow: 'hidden',
                                backgroundColor: '#ddd'
                            }}><img style={{
                                display: 'block',
                                width: '100%'
                            }} src={this.state.portrait} /></div>
                            <Button type="ghost">
                                <Icon type="upload" /> 选择并上传头像
                            </Button>
                        </Upload>
                    </FormItem>
                </Form>
            </div>
        )
    }

}
export const _pane2 = createForm()(__pane2);
function noop() {
    return false;
}
class __pane3 extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false,
            passStrength: 'L', // 密码强度
            rePassStrength: 'L'
        };
        this.getPassStrenth = this.getPassStrenth.bind(this);
        this.renderPassStrengthBar = this.renderPassStrengthBar.bind(this);
        this.checkPass = this.checkPass.bind(this);
        this.checkPass2 = this.checkPass2.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.resetFields = this.resetFields.bind(this);
    }
    getPassStrenth(value, type) {
        if (value) {
            let strength;
            // 密码强度的校验规则自定义，这里只是做个简单的示例
            if (value.length < 6) {
                strength = 'L';
            } else if (value.length <= 9) {
                strength = 'M';
            } else {
                strength = 'H';
            }
            if (type === 'password') {
                this.setState({ passBarShow: true, passStrength: strength });
            }
        } else {
            if (type === 'password') {
                this.setState({ passBarShow: false });
            }
        }
    }

    checkPass(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrenth(value, 'password');
        if (form.getFieldValue('password')) {
            form.validateFields(['rePass'], { force: true });
        }
        callback();
    }

    checkPass2(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrenth(value, 'rePass');

        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不一致！');
        } else {
            callback();
        }
    }

    renderPassStrengthBar(type) {
        //const strength = type === 'password' ? this.state.passStrength : this.state.rePassStrength;
        const strength = this.state.passStrength;
        const classSet = classNames({
            'ant-pwd-strength': true,
            'ant-pwd-strength-low': strength === 'L',
            'ant-pwd-strength-medium': strength === 'M',
            'ant-pwd-strength-high': strength === 'H'
        });
        const level = {
            L: '低',
            M: '中',
            H: '高'
        };
        return (
            <div>
                <ul className={classSet}>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-1"> </li>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-2"> </li>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-3"> </li>
                    <span className="ant-form-text">
                        {level[strength]}
                    </span>
                </ul>
            </div>
        );
    }

    handleSubmit(e) {
        const _this = this,
            token = {accessToken:_this.props.user.accessToken};
        _validate(e,_this,function(values){
            const sendData = {
                old:values.oldPW,
                changeto:values.rePass
            };
            _this.props.dispatch(putPW(token,sendData,function(){
                message.success('修改密码成功，请牢记新密码！！',1);
                _this.resetFields()
            },function(res){
                message.error(res.head.msg,1);
                _this.resetFields()
            }))
        });
    }
    resetFields(){
        this.props.form.resetFields();
        this.setState({ passBarShow: false });
    }
    render(){
        const { getFieldProps } = this.props.form;
        const oldPassProps = getFieldProps('oldPW', {
            rules: [
                { required: true,whitespace: true,message: '请输入旧密码，空格无效' },
                { min:6,max:20,whitespace: true,message: '密码为6-20位' },
            ]
        });
        const passProps = getFieldProps('password', {
            rules: [
                { required: true, min:6,max:20,whitespace: true,message: '密码为6-20位' },
                { validator: this.checkPass }
            ]
        });
        const rePassProps = getFieldProps('rePass', {
            rules: [{
                required: true,
                whitespace: true,
                message: '请再次输入密码'
            }, {
                validator: this.checkPass2
            }]
        });
        return (
            <div>
                <Form horizontal form={this.props.form}>
                    <Row>
                        <Col span="18">
                            <FormItem
                                {...formItemLayout}
                                label="原始密码"
                            >
                                <Input {...oldPassProps}
                                    type="password"
                                    onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                                    autoComplete="off"
                                    id="oldPW"
                                />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">
                            <FormItem
                                {...formItemLayout}
                                label="新密码"
                            >
                                <Input {...passProps}
                                  type="password"
                                  onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                                  autoComplete="off" id="password"
                                />
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="确认新密码"
                            >
                                <Input {...rePassProps} type="password"
                                                        onContextMenu={noop} onPaste={noop} onCopy={noop} onCut={noop}
                                                        autoComplete="off" id="rePass"
                                />
                            </FormItem>
                            <FormItem
                              wrapperCol={formItemLayout.noLabel}
                            >
                                <Button type="primary" onClick={this.handleSubmit}>修改密码</Button>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <Button onClick={this.resetFields}>重置</Button>
                            </FormItem>
                        </Col>
                        <Col span="6">
                            {this.state.passBarShow ? this.renderPassStrengthBar('password') : null}
                        </Col>
                    </Row>
                </Form>

            </div>
        )
    }
}
export const _pane3 = createForm()(__pane3);